package com.controller;

import com.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHanlder {
    // 1.浏览器客户端返回的都是json
    //自定义异常处理
//    @ResponseBody
//    @ExceptionHandler(UserNotExistException.class)
//    public Map<String, Object> handleException(Exception e) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", "自定义:用户不存在");
//        map.put("message", e.getMessage());
//        return map;
//    }

    //2.
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request) {

//        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code", 505);
        Map<String, Object> map = new HashMap<>();
        map.put("code", "not:exites");
        map.put("message", e.getMessage());
        request.setAttribute("ext",map);
        return "forward:/error";
    }
}
